<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">楼宇名称：</div>
      <el-input placeholder="请输入内容" class="search-main" v-model="params.name" />
      <el-button type="primary" @click="handleSearch">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="addBuilding">添加楼宇</el-button>
      <el-button @click="exportToExcel">导出Excel</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table
        style="width: 100%"
        :data="buildingList"
      >
        <el-table-column
          type="index"
          label="序号"
        />
        <el-table-column
          label="楼宇名称"
          width="180"
          prop="name"
        />
        <el-table-column
          label="层数"
          prop="floors"
        />
        <el-table-column
          label="在管面积(m²)"
          width="120"
          prop="area"
        />
        <el-table-column
          label="物业费(元/m²)"
          width="120"
          prop="propertyFeePrice"
        />
        <el-table-column
          label="状态"
          :formatter="formatStatus"
        />
        <el-table-column
          label="操作"
          width="120"
        >
          <template #default="scope">
            <el-button
              size="mini"
              type="text"
              @click="edit(scope.row)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="text"
              @click="delBuildingList(scope.row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
        layout="total, prev, pager, next"
        :total="total"
        :page-size="params.pageSize"
        @current-change="pageChange"
      />
    </div>

    <!-- 添加楼宇弹框 -->
    <el-dialog
      title="添加楼宇"
      :visible="dialogVisible"
      width="580px"
      @close="closeDialog"
    >
      <div class="form-container">
        <el-form :model="addForm" :rules="addFormRules" ref="addForm">
          <el-form-item label="楼宇名称" prop="name">
            <el-input v-model="addForm.name" />
          </el-form-item>
          <el-form-item label="楼宇层数" prop="floors">
            <el-input v-model="addForm.floors" />
          </el-form-item>
          <el-form-item label="在管面积" prop="area">
            <el-input v-model="addForm.area" />
          </el-form-item>
          <el-form-item label="物业费" prop="propertyFeePrice">
            <el-input v-model="addForm.propertyFeePrice" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="confirmAdd">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getBuildingListAPI, createBuildingListAPI, delBuildingListAPI, updateBuildingAPI } from '@/api/building'
import { utils, writeFileXLSX } from 'xlsx'
export default {
  name: 'Building',
  data() {
    return {
      params: {
        page: 1,
        pageSize: 10,
        name: ''
      },
      buildingList: [],
      total: 0,
      dialogVisible: false,
      addForm: {
        name: '',
        floors: null,
        area: null,
        propertyFeePrice: null
      },
      addFormRules: {
        name: [
          { required: true, message: '请输入楼宇名称', trigger: 'blur' }
        ],
        floors: [
          { required: true, message: '请输入楼宇层数', trigger: 'blur' }
        ],
        area: [
          { required: true, message: '请输入楼宇面积', trigger: 'blur' }
        ],
        propertyFeePrice: [
          { required: true, message: '请输入楼宇物业费', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async getBuildingList() {
      const { data } = await getBuildingListAPI(this.params)
      this.buildingList = data.rows
      this.total = data.total
    },
    formatStatus(row) {
      const statusMap = {
        0: '租赁中',
        1: '闲置中'
      }
      return statusMap[row.status]
    },
    pageChange(page) {
      this.params.page = page
      this.getBuildingList()
    },
    handleSearch() {
      this.params.page = 1
      this.getBuildingList()
    },
    addBuilding() {
      this.dialogVisible = true
    },
    closeDialog() {
      this.dialogVisible = false
    },
    confirmAdd() {
      this.$refs.addForm.validate(async valid => {
        if (!valid) return
        const fn = this.addForm.id ? updateBuildingAPI : createBuildingListAPI
        const tip = this.addForm.id ? '编辑' : '新增'
        await fn(this.addForm)
        this.$message.success(`${tip}成功`)
        this.params.page = 1
        this.addForm.id = null
        this.getBuildingList()
        this.closeDialog()
      })
    },
    async delBuildingList(id) {
      try {
        await this.$confirm('确认删除当前楼宇吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await delBuildingListAPI(id)
        this.params.page = 1
        this.$message.success('删除成功')
        this.getBuildingList()
      } catch (e) {
        console.log(e)
      }
    },
    edit(row) {
      this.dialogVisible = true
      for (const key in this.addForm) {
        this.addForm[key] = row[key]
      }
      this.addForm.id = row.id
    },
    exportToExcel() {
      /*
      // 创建一个新的工作簿
      const workbook = utils.book_new()
      // 创建一个工作表，要求一个对象数组格式
      const worksheet = utils.json_to_sheet([
        { name: '张三', age: 18 },
        { name: '李四', age: 20 }
      ])
      // 把工作表添加到工作簿 Data为工作表名称
      utils.book_append_sheet(workbook, worksheet, 'Data')
      // 改写表头
      utils.sheet_add_aoa(worksheet, [['姓名', '年龄']], { origin: 'A1' })
      // 导出方法进行导出
      writeFileXLSX(workbook, 'SheetJSVueAo0.xlsx')
      */

      const workbook = utils.book_new()
      const tableHeader = ['name', 'floors', 'area', 'propertyFeePrice', 'status']
      const tableHeaderValues = ['楼宇名称', '层数', '在管面积(㎡)', '物业费(㎡)', '状态']
      const sheetData = this.buildingList.map(item => {
        const obj = {}
        for (const key of tableHeader) {
          obj[key] = key === 'status' ? this.formatStatus(item) : item[key]
        }
        return obj
      })
      const worksheet = utils.json_to_sheet(sheetData)
      utils.book_append_sheet(workbook, worksheet, 'Data')
      utils.sheet_add_aoa(worksheet, [tableHeaderValues], { origin: 'A1' })
      writeFileXLSX(workbook, 'SheetJSVueAo0.xlsx')
    }
  },
  created() {
    this.getBuildingList()
  }
}
</script>

<style lang="scss" scoped>
.department-container{
  padding:10px;
}
.search-container{
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237,237,237,.9);;
  padding-bottom: 20px;
  .search-label{
    width:100px;
  }
  .search-main{
    width: 220px;
    margin-right: 10px;
  }
}
.page-container{
  padding:4px 0px;
  text-align: right;
}
.create-container{
  margin: 10px 0px;
}
</style>
